﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using XsClient.Common;
using NewLife.Http;

namespace XsClient.Parsers
{
    /// <summary>
    /// BqgResolver
    /// 创建人：zhangyang
    /// 创建时间：2020/6/5 11:10:11
    /// </summary>
    public class BqgResolver : BaseResolver
    {

        public override XsSource Source { get => base.Source; protected set => base.Source = value; }

        protected override string listRegex => @"<li><a\s+href=(?<url>.+?)>(?<content>.+?)</a>(?<content>.+?)</li>";

        protected string list2Regex => @"<li><a\s+href=(?<url>.+?)>(?<content>.+?)</a>(?<content>.+?)</li>";

        protected override string chaperRegex => @"<dd><a\s+href=(?<url>.+?)>(?<content>.+?)</a></dd>";
        /// <summary>
        /// 内容
        /// </summary>
        protected override string contextRegex => "<div id=\"content\">";
        /// <summary>
        /// url
        /// </summary>
        private string bookUrlRegex = "http://[^\\s]*\"";
        /// <summary>
        /// 名称
        /// </summary>
        private string nameRegex = "\">[^\\s]*</a>";
        private string nameRegex2 = "\">.*</a>";
        private string authorRegex = "著[^\\s]*</li>";

        Regex listRx = null;
        Regex chaperRx = null;

        Regex bookRx = null;
        Regex nameRx = null;
        Regex authorRx = null;
        Regex chaperNameRx = null;
        Regex chaperNameRx2 = null;
        Regex chaperUrlRx = null;

        private string bgqtemp = "window.location=";

        string baseUrl = "http://www.loubiqu.com/";
        string baseUrl2 = "https://www.xbiquge.la/";
        public BqgResolver()
        {
            Name = "笔趣阁Info";
            InitSource(1, new XsSource() { BaseUrl = baseUrl, Encoding = "utf8", ID = 1, Name = "笔趣阁Info" });

            seachUrl = Source.BaseUrl + "modules/article/search.php?searchkey={0}";
            listRx = new Regex(listRegex);
            chaperRx = new Regex(chaperRegex);
            bookRx = new Regex(bookUrlRegex);
            nameRx = new Regex(nameRegex);
            authorRx = new Regex(authorRegex);
            chaperUrlRx = new Regex("href=[^\\s]*html");
            chaperNameRx = new Regex("title=[^\\\\s]*\">");
            chaperNameRx2 = new Regex(nameRegex2);
        }
        public override List<BookInfo> Seach(string name)
        {
            string url = string.Format(seachUrl, HttpUtility.UrlEncode(name));
            string htmlStr = Client.GetHtml(url, Source.Encoding);
            return base.Seach(name);
        }
        public override List<BookInfo> FindBooks(string url)
        {
            return base.FindBooks(url);
        }
        public override List<BookInfo> FindBooksByHtml(string html)
        {
            if (html.Contains(bgqtemp))
            {
                string tempkey = html.Substring(html.IndexOf(bgqtemp) + bgqtemp.Length + 2, 50);
                tempkey = tempkey.Substring(0, tempkey.IndexOf("\"") - 1);
                html = Client.GetHtml(Source.BaseUrl + tempkey, Source.Encoding);

            }
            var collection = listRx.Matches(html);
            if (collection != null && collection.Count > 0)
            {
                List<BookInfo> books = new List<BookInfo>();
                foreach (Match item in collection)
                {
                    try
                    {
                        string value = item.Value;
                        string url = bookRx.Match(value).Value.Trim('"');
                        string name = nameRx.Match(value).Value.Substring(2).Replace("</a>", "");
                        string author = authorRx.Match(value).Value.Substring(2).Replace("</li>", "");
                        BookInfo info = new BookInfo()
                        {
                            BaseUrl = url,
                            Name = name,
                            Author = author,
                            SourceID = Source.ID
                        };

                        books.Add(info);
                    }
                    catch (Exception ex)
                    {
                        NewLife.Log.XTrace.WriteException(ex);
                    }
                }
                return books;
            }
            return FindSeachBooks2(html);
        }

        private const string seachTRRegex2 = "<tr>.*?</tr>";

        private const string seachNameRegex2 = "<td class=\"odd\">(?<content>.+?)</td>";
        private Regex seachNameRx = new Regex(seachNameRegex2);
        private Regex seachTrRx = new Regex(seachTRRegex2);
        private List<BookInfo> FindSeachBooks2(string htmlStr)
        {
            List<BookInfo> books = new List<BookInfo>();

            int tbStart = htmlStr.IndexOf("<table class=\"grid\"");
            if (tbStart > 0)
            {
                int trS = htmlStr.IndexOf("<tr>", tbStart);
                //var trList= seachTrRx.Matches(htmlStr);
                //if (trList == null)
                //    return null;
                while (trS > 0)
                    //for (int k=0;k< trList.Count;k++)
                {
                    //string tmpStr = trList[k].Value;
                    int trE = htmlStr.IndexOf("</tr>", trS);
                    string tmpStr = htmlStr.Substring(trS, trE - trS - 1);
                    var collection = seachNameRx.Matches(tmpStr);
                    if (collection != null && collection.Count > 0)
                    {
                        for (int i = 0; i < collection.Count; i += 3)
                        {
                            try
                            {
                                var item = collection[i];
                                var itemAuthor = collection[i + 1];
                                string value = item.Value;
                                string value2 = itemAuthor.Value;
                                if (value.IndexOf("href=") < 0)
                                    continue;
                                int sid = value.IndexOf("href=\"");
                                int sid2 = value.IndexOf("\">",sid);
                                //int sid3 = value.IndexOf("</a></td>", sid);
                                string url = value.Substring(sid + 6, sid2 - sid - 6).Trim();
                                string name = value.Substring(sid2 + 2, value.Length - sid2 - 11).Trim();
                                string author = value2.Substring(16, value2.Length - 21).Trim();
                                BookInfo info = new BookInfo()
                                {
                                    BaseUrl =this.Source.BaseUrl.TrimEnd('/')+'/'+ url.TrimStart('/'),
                                    Name = name,
                                    Author = author,
                                    SourceID = Source.ID
                                };

                                books.Add(info);
                            }
                            catch (Exception ex)
                            {
                                NewLife.Log.XTrace.WriteException(ex);
                            }
                        }
                    }
                    trS = htmlStr.IndexOf("<tr>", trE);
                }
                return books;
            }

            return books;

        }

        public override List<ChaperInfo> FindChapers(ref string url)
        {
            string bookUrl = url;
            string htmlStr = Client.GetHtml(ref bookUrl, Source.Encoding);
            if (htmlStr == null)
                return null;
            if (htmlStr.Contains(bgqtemp))
            {
                string tempkey = htmlStr.Substring(htmlStr.IndexOf(bgqtemp) + bgqtemp.Length + 2, 50);
                tempkey = tempkey.Substring(0, tempkey.IndexOf("\"") - 1);
                bookUrl = Source.BaseUrl + tempkey;
                htmlStr = Client.GetHtml(ref bookUrl, Source.Encoding);
            }
            GetBaseUrl(bookUrl);
            url = bookUrl;
            var collection = chaperRx.Matches(htmlStr);
            if (collection != null && collection.Count > 0)
            {
                List<ChaperInfo> chapers = new List<ChaperInfo>();
                int i = 0;
                foreach (Match item in collection)
                {
                    try
                    {
                        string value = item.Value;
                        string itemUrl = chaperUrlRx.Match(value).Value.Substring(6);
                        string nameStr = chaperNameRx.Match(value).Value;
                        string name = null;
                        if (string.IsNullOrEmpty(nameStr))
                        {
                            if (value.IndexOf("title") >= 0)
                            {

                                nameStr = value.Substring(value.IndexOf("title"), value.IndexOf("\">") - value.IndexOf("title"));
                                name = nameStr.Substring(7).Replace("\">", "");
                            }
                            else
                            {

                                name = chaperNameRx2.Match(value).Value.Substring(2).Replace("</a>", "");
                            }
                        }
                        else
                            name = nameStr.Substring(7).Replace("\">", "");

                        ChaperInfo chaper = new ChaperInfo() { ID = i++, Url = url.TrimEnd('/') + "/" + itemUrl, Name = name };
                        if (url.Contains("xbiquge.la"))
                        {
                            chaper.Url = baseUrl2.TrimEnd('/') + "/" + itemUrl;
                        }
                        chaper.SourceID = Source.ID;
                        chapers.Add(chaper);
                    }
                    catch (Exception ex)
                    {
                        NewLife.Log.XTrace.WriteException(ex);
                    }

                }
                return chapers;
            }
            return null;
        }

        public override string GetContext(string url)
        {
            string htmlStr = Client.GetHtml(url, Source.Encoding);

            int startIndex = htmlStr.IndexOf(contextRegex);
            if (startIndex > 0)
            {
                int endIndex = htmlStr.IndexOf("<!--over-->", startIndex + 27);
                if (endIndex < 0)
                {//xbiquge.la
                    endIndex = htmlStr.IndexOf("</div>", startIndex + 27);
                }
                return htmlStr.Substring(startIndex + 27, endIndex - startIndex - 27).Replace("<br>", "\n").Replace("<br/>", "\n").Replace("&nbsp;", " ").Replace("\n\n", "\n").Replace("\n\n", "\n");
            }

            return null;
        }
    }
}
